import {
	defineStore
} from 'pinia';
import {
	cookie
} from '@/utils/cookie.js'
import apis from "@/apis/index.js";

export const useAppStore = defineStore('app', {
	state: () => ({
		isInApp: cookie.get('isInApp'),
		token: cookie.get('token'),
		userStateInfo: null,
		sysMsgCount: 0,
	}),
	actions: {
		SetInAppType(value) {
			cookie.set('isInApp', value)
			this.isInApp = value
		},
		SetAppToken(value) {
			cookie.set('token', value)
			this.token = value
			console.log('this.token', this.token)
		},
		getNavBarHeight() {
			let navbarHeight = 0
			// #ifdef MP-WEIXIN
			let menuButtonInfo = uni.getMenuButtonBoundingClientRect();
			// 导航栏高度 = 胶囊高度 + 上间距 + 下间距 + 微调	（menuButtonInfo.top - uni.getSystemInfoSync()['statusBarHeight'] = 上间距）
			navbarHeight =
				menuButtonInfo.height +
				(menuButtonInfo.top - uni.getSystemInfoSync()["statusBarHeight"]) * 2 +
				2;
			// #endif
			// // #ifdef APP-PLUS || H5
			navbarHeight = 45;
			// #endif
			return navbarHeight;
		},
		// 获取状态栏高度
		geStatusBarHeight() {
			return uni.getSystemInfoSync()["statusBarHeight"];
		},
		async refreshUserInfo() {
			const {
				data
			} = await apis.selectUserInfo();
			this.userStateInfo = data;
		},
		async updateUserInfo(userInfo) {
			await apis.updateUserInfo(userInfo);
			Object.keys(userInfo).forEach(key => {
				this.userStateInfo[key] = userInfo[key];
			});
		},
		async logout() {
			await apis.logout();
			cookie.remove('token');
			this.token = null;
			this.userStateInfo = null;
		},
		async updateSysMsgCount(){
		 	const {data} = await apis.getSystemMessageNoReadStateNumber();
			this.sysMsgCount = data;
		},
		async readSysMsg(id){
			await apis.updateSystemMessageState(id);
			await this.updateSysMsgCount();
		}
	},
	getters: {
		GETTOKEN: (state) => state.state,
		GETInAppType: (state) => state.isInApp,
		userInfo: state => state.userStateInfo,
		userId: state => state.userInfo?.id,
		isLogin: state => !!state.token,
		msgCount: state => state.sysMsgCount
	},
});